import { ApiResponse, SearchResult } from '@/types/data'
import { HistoryAction, RootThunkAction } from '@/types/store'
import axios from '@/utils/request'
export function getSuggestion(keyword: string): RootThunkAction {
  return async (dispatch) => {
    const res = await axios.get<ApiResponse<{ options: string[] }>>(
      '/suggestion',
      {
        params: {
          q: keyword,
        },
      }
    )
    // console.log(res.data.data.options)
    dispatch({
      type: 'history/saveSuggestion',
      payload: res.data.data.options,
    })
  }
}
/**
 * 清空推荐列表
 * @returns
 */
export function clearSuggestion(): HistoryAction {
  return {
    type: 'history/clearSuggestion',
  }
}
/**
 * 添加历史记录
 * @param params
 * @returns
 */
export function addHistory(params: string): RootThunkAction {
  return (dispatch, getState) => {
    // 获取redux 中的旧数据
    let { histories } = getState().history
    // 历史记录 过滤掉相同的数据
    histories = histories.filter((item) => item !== params)
    // 再判断数据是否大于10条 大于删除最后一条 添加最新的数据
    if (histories.length >= 10) {
      histories.pop()
    }
    histories.unshift(params)
    //
    dispatch({
      type: 'history/saveHistory',
      payload: histories,
    })
  }
}
/**
 * 移除历史记录
 * @param params
 * @returns
 */
export function removeHistory(params: string): RootThunkAction {
  return (dispatch, getState) => {
    // 获取redux 中的旧数据
    let { histories } = getState().history
    // 历史记录 过滤掉相同的数据
    histories = histories.filter((item) => item !== params)
    dispatch({
      type: 'history/saveHistory',
      payload: histories,
    })
  }
}
/**
 * 清空历史记录
 * @param params
 * @returns
 */
export function cleatHistory(): HistoryAction {
  return {
    type: 'history/saveHistory',
    payload: [],
  }
}

/**
 * 获取搜索结果
 * @param keyword
 * @param page
 * @param per_page
 * @returns
 */
export function getSearchResult(
  keyword: string,
  page = 1,
  per_page = 10
): RootThunkAction {
  return async (dispatch) => {
    const res = await axios.get<ApiResponse<SearchResult>>('/search', {
      params: {
        q: keyword,
        page,
        per_page,
      },
    })
    dispatch({
      type: 'history/saveSearchResult',
      payload: res.data.data,
    })
  }
}
